/**
 * Created by evilb on 2017/5/22.
 */
import axios from 'axios'
import qs from 'qs'

axios.defaults.baseURL = "/api";
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

export default {
  get(url, data){
    let b = true;
    for (let key in data) {
      if (b) {
        url += `?${key}=${data[key]}`;
        b = !b;
      }
      else
        url += `&${key}=${data[key]}`
    }

    return new Promise((resolve, reject) => {
      axios.get(url)
        .then(res => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        })
    })
  },
  post(url, data){
    return new Promise((resolve, reject) => {
      axios.post(url, qs.stringify(data))
        .then(res => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        })
    })
  },
  put(url, data){
    return new Promise((resolve, reject) => {
      axios.put(url, qs.stringify(data))
        .then(res => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        })
    })
  },
  patch(url, data){
    return new Promise((resolve, reject) => {
      axios.patch(url, qs.stringify(data))
        .then(res => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        })
    })
  },
  delete(url, data){
    let b = true;
    for (let key in data) {
      if (b) {
        url += `?${key}=${data[key]}`;
        b = !b;
      }
      else
        url += `&${key}=${data[key]}`
    }

    return new Promise((resolve, reject) => {
      axios.delete(url)
        .then(res => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        })
    })
  }
}
